package com.mall.gateway.config;

import com.mall.gateway.handler.GatewayExceptionHandler;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.WebProperties;
import org.springframework.boot.web.reactive.error.DefaultErrorAttributes;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;

import java.util.Collections;
import java.util.List;

/**
 * 网关异常配置类
 */
@Configuration
public class GatewayErrorConfig {

    /**
     * 注入默认的ErrorAttributes bean
     *
     * @return ErrorAttributes实例
     */
    @Bean
    public ErrorAttributes errorAttributes() {
        return new DefaultErrorAttributes();
    }

    /**
     * 注入HttpMessageConverters bean
     *
     * @return HttpMessageConverters实例
     */
    @Bean
    public HttpMessageConverters httpMessageConverters() {
        return new HttpMessageConverters();
    }

    /**
     * 自定义异常处理
     *
     * @param errorAttributes 错误属性
     * @param applicationContext 应用上下文
     * @param serverCodecConfigurer 服务编码配置
     * @param viewResolversProvider 视图解析器
     * @return 异常处理器
     */
    @Bean
    @Order(-1)
    public ErrorWebExceptionHandler errorWebExceptionHandler(ErrorAttributes errorAttributes,
                                                             ApplicationContext applicationContext,
                                                             ServerCodecConfigurer serverCodecConfigurer,
                                                             ObjectProvider<List<ViewResolver>> viewResolversProvider) {
        GatewayExceptionHandler exceptionHandler = new GatewayExceptionHandler(
                errorAttributes,
                new WebProperties().getResources(),
                new ErrorProperties(),
                applicationContext);
        
        exceptionHandler.setViewResolvers(viewResolversProvider.getIfAvailable(Collections::emptyList));
        exceptionHandler.setMessageWriters(serverCodecConfigurer.getWriters());
        exceptionHandler.setMessageReaders(serverCodecConfigurer.getReaders());
        
        return exceptionHandler;
    }
}